<template>
  <div id="enterInfoSec" v-loading.fullscreen.lock="fullscreenLoading">
    <h2>信息录入</h2>
    <div class="selects">
      <el-select filterable v-model="projectId" placeholder="选择项目">
        <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-input placeholder="选择企业" disabled v-model="chooseComed"></el-input>
      <el-button type="primary" @click="chooseCom">选择企业</el-button>
    </div>

    <section class="part">
      <h3>资产信息</h3>
      <div class="tabledata">
        <span class="tit">基础交易票据</span>
        <el-table :data="basicData" border>
          <el-table-column
            align="center"
            v-for="(item, index) in tableCols"
            :key="index"
            :prop="item.prop"
            :label="item.label"
          ></el-table-column>
          <el-table-column  label="乐税查验">
            <template slot-scope="scope">
              <!-- <el-tag
                v-if="scope.row.tag"
                :type="scope.row.tag === '查验成功' ? 'success' : 'primary'"
                disable-transitions
              >{{scope.row.tag}}</el-tag> -->

              <el-tag v-if="scope.row.lsCheck == '1'" type='success' size="small">查验通过</el-tag>
              <el-tag v-if="scope.row.lsCheck == '9'" type='warning' size="small">查验失败</el-tag>
              <span v-if="scope.row.lsCheck == '0'" style="color: red;">未查验</span>
            </template>
          </el-table-column>
          <el-table-column prop="ocr" label="OCR识别">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.ocr === '识别成功' ? 'success' : 'primary'"
                disable-transitions
              >{{scope.row.ocr}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="preview(scope.row)" class="view" type="text" size="small">查看</el-button>
              <!-- <el-button
                @click="checkOcr(scope.row,$index)"
                :disabled="isChecked == '已查验'"
                class="view"
                type="text"
                size="small"
              >{{isChecked}}</el-button> -->
              <el-button v-if="scope.row.lsCheck == '0'" @click="checkOcr(scope.row, scope.$index)" class="view" type="text" size="small">查验</el-button>
              <el-button v-if="scope.row.lsCheck == '1'"  class="view" type="text" size="small">查验通过</el-button>
              <el-button v-if="scope.row.lsCheck == '99'"  class="view" type="text" size="small">查验失败</el-button>
              <el-button @click="delbain(scope.$index)" class="view" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-upload
          class="upload-demo"
          style="text-align: center;margin-top: 30px"
          :action="imgUrl"
          :before-upload="beforeLoading"
          :on-success="fileUploadSuc"
          :data="expedata"
          accept="image/jpeg, image/png, image/bmp"
          :file-list="ocrFiles"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </div>
    </section>
    <section class="part">
      <div class="tabledata">
        <span style="margin-top: 30px" class="tit">应收款附件</span>
        <el-table :data="fujianFiles" border>
            <el-table-column label="ID">
            <template slot-scope="scope">
                {{scope.$index+1}}
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            v-for="(item, index) in fileCols"
            :key="index"
            :prop="item.prop"
            :label="item.label"
          ></el-table-column>
         <el-table-column label="操作">
             
            <template slot-scope="scope">
              <el-button @click="delysfj(scope.row, scope.$index)" class="view" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button @click="uploadAdd" class="uploadbtn" type="primary">上传</el-button>
      </div>
    </section>
    <el-button class="postadd" @click="postAdd" type="warning">提交</el-button>
    <el-dialog title="上传" center :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form label-position="right" label-width="120px" :model="formData">
        <el-form-item label="文件名称：">
          <el-input v-model="formData.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- <el-upload style="text-align: center" 
                list-type="picture-card"
                :action="imgUrlT"
                :before-upload='beforeLoadingT'
                :on-success='fileUploadSuct'>
                <i class="el-icon-plus"></i>
                <div style="position: relative;top: -50px;line-height: 0" class="el-upload__text">点击上传</div>
      </el-upload>-->
      <div style="text-align: center;">
        <el-button type="warning" size="small" @click="clickBtn">点击上传</el-button>
        <input type="file" class="img_input" ref="portrait" @change="selectFile" />
      </div>
      <div style="text-align: center;">
        <span>{{formData.title}}</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="addPic" type="primary" @click="dialog2sure">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑" center :visible.sync="dialogFirstVisible"  :before-close="handleClose">
      <el-form label-position="right" :model="formData2" label-width="120px" >
        <el-form-item label="发票代码：" >
          <el-input v-model="formData2.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="发票号码：" >
          <el-input v-model="formData2.num" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="开票时间：" prop="date">
          <el-date-picker
            style="width: 100%;"
            v-model="formData2.date"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="校验码：" >
          <el-input v-model="formData2.check" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="中登次数：" >
          <el-input v-model="formData2.nums" placeholder="请输入次数" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button class="addPic" type="primary" @click="pushOcrData">确 认</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>

    <el-dialog :visible.sync="dialogTable" width="900px">
      <div class="swdyTops">
        <span class="search">搜索公司：</span>
        <el-input class="elinput" size="small" placeholder="请输入公司关键字" v-model="search"></el-input>
        <el-button class="gocreat" size="small" type="primary" @click="searchCompany">搜索</el-button>
        <span class="sousuo">搜索不到？</span>
        <el-button class="gocreat" size="small" type="primary" @click="goChuangjian">去创建</el-button>
      </div>
      <div class="diatable">
        <el-table :data="diatableData" border style="width: 100%">
          <el-table-column prop="clientId" label="序号" align="center"></el-table-column>
          <el-table-column prop="companyName" label="客户名称" align="center"></el-table-column>
          <el-table-column prop="lsCheck" label="中登查询" align="center"></el-table-column>
          <el-table-column prop="regDate" label="中登更新时间" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="choose(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="10"
            layout="total, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      chooseComed: "",
      dialogTable: false,
      search: "",
      diatableData: [],
      currentPage: 1,
      total: 0,
      fullscreenLoading: false,
      //  rules: {
      //     code: [{ required: true,  trigger: 'blur' }],
      //     num: [{ required: true,  trigger: 'blur' }],
      //     date: [{ required: true,  trigger: 'blur' }],
      //     nums: [{ required: true,  trigger: 'blur' }],
      //     check: [{ required: true,  trigger: 'blur' }]
      //     },
      basicData: [
        // {name: 1, tag: '查验成功', ocr: '识别成功'}
      ],
      tableCols: [
        { label: "票据编号", prop: "code" },
        { label: "票据名称", prop: "name" },
        { label: "开票日期", prop: "date" },
        { label: "附件名称", prop: "filename" },
        { label: "转让金额", prop: "money" },
        { label: "发票金额", prop: "money" },
        { label: "核实", prop: "user" },
        { label: "中登次数", prop: "nums" },
      ],
      fujianFiles: [],
      fileCols: [
        // { label: "ID", prop: "id" },
        { label: "附件类型", prop: "attachmentType" },
        { label: "文件名称", prop: "title" },
        { label: "上传用户", prop: "uploadUser" },
        { label: "上传时间", prop: "uploadDate" }
      ],
      formData2: {
          code: '',
          num: '',
          date: '',
          check: '',
          nums: ''
      },
      formData2c: {
          code: '',
          num: '',
          date: '',
          check: '',
          nums: ''
      },
      dialogFormVisible: false,
      //下面的dialog
      formData: {
        name: "",
        title: ""
      },
      tempDiadata2: {},
      dialogImageUrl: "",
      dialogVisible: false,
      ocrFiles: [],
      imgUrl: this.$imgUrlT,
      imgUrlT: this.$imgUrl,
      dialogFirstVisible: false,
      loading: null,
      expedata: { folder: "bill" },
      isChecked: "查验",
      options: [],
      projectId: "",
      clientId: "",
    };
  },
  mounted() {
    this.$api.apiGetCustomerList().then(({ data }) => {
      this.options = data.data;
    });
  },
  methods: {
      delbain (index) {
          this.basicData.splice(index, 1);
      },
      delysfj(item, index) {
          this.fujianFiles.splice(index, 1);
      },
    clickBtn(item, index) {
      this.tempItem = item;
      this.tempIndex = index;
      let file = this.$refs.portrait;
      file.value = "";
      // file.outerHTML = file.outerHTML
      this.$refs.portrait.click();
    },
    selectFile: function(e) {
      // this.info.voucher = e.target.files[0].name; // 获取图片的名字
      this.file = e.target.files[0]; // 获取图片的所有属性
      // let reader = new FileReader();
      // reader.addEventListener('load', () => {
      //   this.userImg = reader.result;
      // }, false);
      // if (this.file) {
      //   reader.readAsDataURL(this.file);
      // }
      let fm = new window.FormData(); // 创建一个表单
      fm.append("file", this.file); // apend到这个字段,后台凭证接受的字段
      // fm.append('ids', this.$route.query.id); // apend到这个字段，后台id接受的字段
      this.fullscreenLoading = true;
      axios
        .post(this.imgUrl, fm, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(({ data }) => {
          if (data.code == 200) {
            this.tempDiadata2 = data.data;
            this.formData.title = data.data.originName;
          }
          this.fullscreenLoading = false;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    dialog2sure() {
        if (!this.formData.name) {
             this.$message({
          type: "warning",
          message: "请输入文件名称"
        });
            return false;
        }
         if (!this.formData.title) {
             this.$message({
          type: "warning",
          message: "请上传文件"
        });
            return false;
        }
        let data = this.tempDiadata2;
      let fujian = {
        // id: this.fujianFiles.length+1,
        attachmentType: data.state == 1 ? "图片" : "文件",
        title: this.formData.name,
        path: data.filePath,
        uploadDate: this.$moment(new Date()).format("YYYY-MM-DD"),
        uploadUser: JSON.parse(sessionStorage.getItem("user")).name
      };
      this.fujianFiles.push(fujian);
      this.dialogFormVisible = false;
      this.formData = {name: '', title: ''}
    },
    handleClose(done) {
      this.formData = {name: '', title: ''};
      for (let k in this.formData2) {
        this.formData2[k] = this.formData2c[k]
      }
      done();
    },
    choose(val) {
      this.chooseComed = val.companyName;
      this.clientId = val.clientId;
      this.dialogTable = false;
    },
    searchCompany() {
      this.getList(1);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList(val);
    },
    getList(val) {
      this.currentPage = val;
      let obj = {
        companyName: this.search,
        page: this.currentPage
      };
      this.axios
        .get("AdminAPI/project/showClientListForProject", {
          params: this.filterNoneObj(obj)
        })
        .then(({ data }) => {
          console.log(data);
          this.diatableData = data.data;
          this.total = data.pageInfo.total;
        });
    },
    chooseCom(val) {
      // this.type = val;
      this.dialogTable = true;
      this.getList(1);
    },
    goChuangjian() {
      this.$router.push("/home/enterInfo");
    },
    checkOcr(row,index) {
      let param = {
        invoiceCode: row.code,
        invoiceNumber: row.num,
        billTime: row.date,
        checkCode: row.check
      };
      this.loading = this.$loading({
        lock: true,
        text: "乐税查验中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      this.$api.apiCheckFa(param).then(res => {
        if (res != undefined) {
         
          this.loading.close();
          let { data } = res.data;
          if (data.RtnCode == '240') {
              this.$message({message: '余额不足,请充值',type: 'warning'});
              return false;
          }
          if (data.RtnCode == 1000 || data.RtnCode == 2001) {
              row.isChecked = "99"
            this.$message({message: '查验失败',type: 'warning'});
            this.basicData.splice(index, 1);
            return false;
          }
        //    this.$message({
        //     type: "success",
        //     message: "查验成功"
        //   });
          row.money = res.data.data.totalTaxSum;
          row.name = data.invoiceTypeName;
        //   row.tag = "查验成功";
          row.isChecked = "1"
        }
      });
    },
    postAdd() {
      let receiptjson = [];
      this.basicData.forEach((item, index) => {
        let receipt = {
          receiptNo: item.num,
          name: item.name,
          invoiceDate: item.date,
          attachName: "发票",
          transferAmount: item.money,
          invoiceAmount: item.money,
          lsCheck: item.lsCheck,
          isVerify: "",
          zdCheckTimes: item.nums,
          isClientUpload: "", //客户上传
          lsCheck: item.lsCheck,
          ocrState: item.ocr,
          invoicePath: item.fileurl,
          receiptCode: item.code,
          checkNo: item.check
        };
        receiptjson.push(receipt);
      });
      let param = {
        receiptJson: JSON.stringify(receiptjson),
        attachmentJson: JSON.stringify(this.fujianFiles),
        clientId: this.projectId,
        projectId: this.clientId
      };
      this.$api.apiAddProperty(param).then(res => {
        if (res.data.code == 200) {
          this.$message({
            type: "success",
            message: "提交成功"
          });
        this.projectId= '';
        this.chooseComed = '';
         this.basicData= [];
         this.fujianFiles = [];
        }
      });
    },
    beforeLoading(file) {
      let size = Number((file.size / 1024 / 1024).toFixed(2));

      if (size > 4) {
        this.$message({
          type: "warning",
          message: "文件大小不得超过4M, 请重新上传"
        });
        return;
      }
      this.loading = this.$loading({
        lock: true,
        text: "文件上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    },
    beforeLoadingT() {
      if (this.formData.name == "") {
        this.$message({
          type: "warning",
          message: "请输入文件名称"
        });
        return false;
      }
      this.loading = this.$loading({
        lock: true,
        text: "文件上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    },
    uploadAdd() {
      this.dialogFormVisible = true;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    fileUploadSuc({ data }, file, fileList) {
      console.log(this.fileList);
      let param = {
        fileUrl: data.filePath
      };
      this.loading.text = "OCR识别中...";
      this.$api
        .apiOrcSearch(param)
        .then(res => {
          let resdata = res.data.data;
          resdata.filename = "发票";
          resdata.ocr = "识别成功";

          this.loading.close();
        //   this.formData2 = Object.assign(resdata);
        for(let k in resdata) {
            this.formData2[k]= resdata[k]
        }
          this.formData2.fileurl = data.filePath;
          this.dialogFirstVisible = true;
        })
        .catch(err => {
          this.loading.close();
        });
    },
    pushOcrData() {
      this.formData2.date = this.$moment(new Date(this.formData2.date)).format(
        "YYYY-MM-DD"
      );
      let status = true;
      // console.log(this.formData2);
      for (let k in this.formData2) {
          if (!this.formData2[k] && k != 'lsCheck') {
              status = false;
          }
      }
      if (!status) {
           this.$message({message: '请补充完整表格',type: 'warning'});
          return false;
      }
      this.dialogFirstVisible = false;
      this.formData2.lsCheck = '0';

      let temobj = JSON.parse(JSON.stringify(this.formData2))
      this.basicData.push(temobj);
      console.log(this.basicData);
      console.log(this.formData2);
      for (let k in this.formData2) {
        this.formData2[k] = ''
      }
    },
    fileUploadSuct({ data }, file, fileList) {
      // 应收附件上传

      this.loading.close();
      this.$message({
        type: "success",
        message: "上传成功"
      });
      let len = this.fujianFiles.length;

      let fujian = {
        id: len + 1,
        attachmentType: data.state == 1 ? "图片" : "文件",
        title: this.formData.name,
        path: data.filePath,
        uploadDate: this.$moment(new Date()).format("YYYY-MM-DD"),
        uploadUser: JSON.parse(sessionStorage.getItem("user")).name
      };
      this.fujianFiles.push(fujian);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    preview(row) {
      this.dialogImageUrl = this.$viewImg + row.fileurl;
      this.dialogVisible = true;
    }
  }
};
</script>
<style lang="scss">
#enterInfoSec {
  h2 {
    background: white;
    padding: 15px;
  }
  .selects {
    width: 90%;
    margin: 20px auto 0;
    display: flex;
    .el-input {
      width: 250px;
      &:first-child {
        margin-right: 20px;
      }
    }
  }
  .el-form {
    .el-select {
      display: block;
    }
  }

  .part {
    padding: 0;
    padding-bottom: 30px;
    h3 {
      background: #e2eefd;
      padding: 12px;
    }
    .tabledata {
      width: 90%;
      margin: 30px auto;
      .uploadbtn {
        width: 24%;
        margin: 30px auto;
        display: block;
      }
    }
  }
  .postadd {
    width: 25%;
    margin: 40px auto;
    display: block;
  }
  .addPic {
    width: 30%;
  }
  .el-upload-list {
    display: none;
  }
  .el-upload {
    width: 24%;
    button {
      width: 100%;
      padding: 14px;
    }
  }

  .swdyTops {
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #b9b9b9;
    padding-bottom: 26px;
    .el-input {
      width: 160px;
    }
    .sousuo {
      margin: 0 40px;
    }
  }
  .diatable {
    margin-top: 10px;
    background: white;
    padding-top: 16px;
    .has-gutter tr th {
      background: #fefaf1;
    }
    .block {
      text-align: right;
      margin-right: 55px;
      height: 50px;
      margin-top: 20px;
    }
  }
  .img_input {
    position: absolute;
    left: -2000px;
    top: -100px;
  }
}
</style>
